package popcorn.ticket.serviceimpl;

import java.net.InetAddress;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import popcorn.ticket.dao.LogsMapper;
import popcorn.ticket.dao.OrdersMapper;
import popcorn.ticket.dao.TicketMapper;
import popcorn.ticket.entity.Logs;
import popcorn.ticket.entity.Orders;
import popcorn.ticket.entity.OrdersExample;
import popcorn.ticket.entity.Ticket;
import popcorn.ticket.service.MembersService;
import popcorn.ticket.service.OrdersService;
import popcorn.ticket.service.TicketService;
import popcorn.ticket.tool.AjaxResponse;
import popcorn.ticket.tool.GetEndTimeTools;
import popcorn.ticket.tool.PageData;

@Service
public class OrdersServiceImpl implements OrdersService {
	@Autowired
	OrdersMapper omapper;
	
	@Autowired
	TicketMapper tmapper;
	
	@Autowired
	private TicketService ts;
	
	@Autowired
	private MembersService ms;
	
	@Autowired
	private LogsMapper lm;

	AjaxResponse ar = new AjaxResponse();

	// 添加
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public AjaxResponse add(Orders record) {
		try {
			// 同步代码块
			synchronized (this) {
				
				// 判断用户买了几个座位
				int s = record.getSeat().indexOf(",");
				if (s != -1) {
					// 用户买了2个座位
					// 获取座位
					String seat = record.getSeat();
					// 拆分座位
					String[] array = seat.split(",");
					// 查询是否有该座位
					for (int i = 0; i < 2; i++) {
						// 判断数据库里座位是否还存在，如果存在，就添加，否则，回滚
						int scount = omapper.selectSeatCount(array[i]);
						// 判断是否有座位
						if (scount != 0) {
							// 没有座位
							// 回滚
							System.out.println(1 / 0);
						}
					}
				} else {
					// 用户买了一个座位
					// 判断数据库里座位是否还存在，如果存在，就添加，否则，回滚
					int scount = omapper.selectSeatCount(record.getSeat());
					// 判断是否有座位
					if (scount != 0) {
						// 没有座位
						// 回滚
						System.out.println(1 / 0);
					}
				}	
				// 上面的判断有座位的话，执行添加订单
				int n = omapper.insert(record);
				// 判断是否下单成功
				// System.out.println(1 / n);
			}

			// 获取ip
			InetAddress ia = InetAddress.getLocalHost();
			// 日志
			Logs logs = new Logs();
			// ip地址
			logs.setLogip(ia + "");
			logs.setLogobject("orders");
			logs.setLogop("添加订单");
			logs.setLogtime(new Date());
			logs.setRemark("用户下单成功");
			logs.setUsers(record.getUsers());
			int l = lm.insert(logs);
			// 判断日志是否添加成功
			System.out.println(1 / l);

			ar.setCode(200);
			ar.setMsg("添加成功");
			return ar;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ar.setCode(0);
			ar.setMsg("添加失败");
			return ar;
		}

	}

	// 动态修改
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public AjaxResponse updOrders(Orders record) {

		try {
			// 修改状态
			int n = omapper.updateByPrimaryKeySelective(record);
			// 判断是否修改成功
			 System.out.println(1 / n);
			// 支付操作
			if (record.getOrderstatus() != null && record.getOrderstatus() == 1) {
				InetAddress ia = InetAddress.getLocalHost();
				// 日志
				Logs logs = new Logs();
				// ip地址
				logs.setLogip(ia + "");
				logs.setLogobject("orders");
				logs.setLogop("修改订单");
				logs.setLogtime(new Date());
				logs.setRemark("用户支付成功");
				logs.setUsers(record.getUsers());
				// 添加日志
				int l = lm.insert(logs);
				// 判断日志是否成功
				System.out.println(1 / l);
				
				int userid = record.getUsers().getUserid();
				double integral = record.getOrderprice();
				// 会员积分增加
				ms.updateMemberIntegerByUserid(userid, integral,"+");
				
				// 判断用户买了几个座位
				int s = record.getSeat().indexOf(",");
				if (s != -1) {
					String[] seats = record.getSeat().split(",");
					// 生成2张影票
					// 生成影票给tk赋值
					Ticket tk1 = new Ticket(0, record, seats[0],0, 1);// 影票状态0表示未取票，影票显示状态1表示显示
					Ticket tk2 = new Ticket(0, record, seats[1],0, 1);
					AjaxResponse ar1 = ts.insert(tk1);
					AjaxResponse ar2 = ts.insert(tk2);
					// 判断
					if (ar1.getMsg().equals("生成成功") && ar2.getMsg().equals("生成成功")) {
						ar.setCode(200);
						ar.setMsg("修改成功");
						return ar;
					}
					// 否则回滚
					System.out.println(1 / 0);
				} else {
					// 生成1张影票
					Ticket tk = new Ticket(0, record, record.getSeat(),0, 1);
					AjaxResponse ar = ts.insert(tk);
					// 判断
					if (ar.getMsg().equals("生成成功")) {
						ar.setCode(200);
						ar.setMsg("修改成功");
						return ar;
					}
					// 回滚
					System.out.println(1 / 0);
				}
			}
			// 管理员还原显示状态
			if (record.getOrderstatus() == null && record.getOrdercondition() == 1) {
				InetAddress ia = InetAddress.getLocalHost();
				// 日志
				Logs logs = new Logs();
				// ip地址
				logs.setLogip(ia + "");
				logs.setLogobject("orders");
				logs.setLogop("修改订单");
				logs.setLogtime(new Date());
				logs.setRemark("管理员还原用户显示状态");
				logs.setUsers(record.getUsers());
				// 添加日志
				int l = lm.insert(logs);
				// 判断日志是否成功
				System.out.println(1 / l);

			}

			ar.setCode(200);
			ar.setMsg("修改成功");
			return ar;

		} catch (Exception e) {
			// 打印错误消息
			e.printStackTrace();

			ar.setCode(0);
			ar.setMsg("修改失败");
			return ar;
		}

	}

	// 通过主键获取值
	@Override
	public Orders getOrdersById(int orderid) {
		// TODO Auto-generated method stub
		return omapper.selectByPrimaryKey(orderid);
	}

	// 模糊查询+分页
	@Override
	public PageData<Orders> getOrdersByUserName(String moviename,String username, int page, int limit,String seldate,int selstatus) {
		// 调用插件
		PageHelper.startPage(page, limit);

		String startdate=null;
		String enddate = null;
		//对传过来得值进行处理
		//开始日期
		if (!seldate.equals("")) {
			startdate=seldate.substring(0, 10);
			//结束日期
			enddate =seldate.substring(13);
		}

		List<Orders> list = omapper.selectByUserName(moviename, username, startdate, enddate, selstatus);
		// 处理播放时间
		for (int i = 0; i < list.size(); i++) {
			// 利用工具计算结束时间
			list.get(i).setEndtime(GetEndTimeTools.getEndDate(list.get(i).getSchedule().getPlaytime(), list.get(i).getDuration()));
		}

		PageInfo<Orders> pageInfo = new PageInfo<Orders>(list);

		PageData<Orders> pageData = new PageData<Orders>(pageInfo.getList(), page, (int) pageInfo.getTotal(), limit);
		pageData.setCode(0);
		pageData.setMsg("");

		return pageData;
	}
	
	@Override
	/**
	 * 获得单个用户的全部订单
	 */
	public List<Orders> getOrdersByUserId(int userid) {

		return omapper.selectByUserId(userid);
	}
	
	@Override
	/**
	 * 更新订单信息
	 */
	public AjaxResponse updUserOrders(Orders orders) {
		
		AjaxResponse ar = new AjaxResponse("修改失败", 0);
		int n = omapper.updateByPrimaryKeySelective(orders);
		if(n > 0) {
			ar.setCode(200);
			ar.setMsg("修改成功");
		}
		
		return ar;
	}
	
	/**
	 * 获取全部订单
	 */
	@Override
	public List<Orders> getAllOrders() {
		OrdersExample example = new OrdersExample();
		example.createCriteria().andOrderidIsNotNull();
		return omapper.selectByExample(example);
	}
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public int refundOrders(int orderid) {
		
		// 修改订单状态
		Orders order = new Orders();
		order.setOrderstatus(3);
		order.setOrderid(orderid);

		try {
			int n = omapper.updateByPrimaryKeySelective(order);
			// 修改影票状态
			Ticket t = new Ticket();
			t.setOrders(order);
			int n2 = tmapper.updRefundTicket(t);
			// 判断修改是否成功 否则回滚
			System.out.println(1/n);
			System.out.println(1/n2);
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}
	
	
	

}
